package com.qfedu.demo;

import com.qfedu.service.AccountService;
import com.qfedu.util.TransactionManager;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @version 1.0
 * 公众号：Java架构栈
 * @Author: 卓不凡
 */
public class Demo01 {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
        //目标对象
        final AccountService accountService = applicationContext.getBean("accountService", AccountService.class);
        //增强的类执行业务
        final TransactionManager transactionManager = (TransactionManager) applicationContext.getBean("transactionManager");
        //代理对象
        AccountService o = (AccountService) Proxy.newProxyInstance(accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
            //增强业务逻辑
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("transfer".equals(method.getName())){
                    try {
                        //开启事务
                        transactionManager.beginTransaction();
                        //目标方法执行
                        method.invoke(accountService,args);
                        //提交事务
                        transactionManager.commit();
                    } catch (Exception e) {
                        //回滚事务
                        transactionManager.rollback();
                        e.printStackTrace();
                    } finally {
                        transactionManager.release();
                    }
                }
                return null;
            }
        });
        o.transfer("hzy","ysy",1000.0);


    }
}
